const mongo = require("./lib/mongo");
const code = require("./lib/resCode");
const crypto = require('crypto');
const EventEmitter = require('events').EventEmitter;
const SMSClient = require('@alicloud/sms-sdk');
module.exports = async ()=>{
    try{
        //初始化全局函数
        global.fun = {
            randomString:function(len = 8) {
                let chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
                let res = "";
                for (let i = 0; i < len; i++) {
                    let id = Math.ceil(Math.random() * 35);
                    res += chars[id];
                }
                return res;
            },
            sleep : (time)=>{
                return new Promise( (resolve, reject) =>{
                    setTimeout(function(){resolve(null)}, time * 1000)
                })
            },
            encord2md5:(string)=>{
                let ms5Str = crypto.createHash('sha1').update(string).digest('hex');
                let salt = global.fun.randomString();
                let password = crypto.createHash('sha1').update(ms5Str + salt).digest('hex');
                return {password, salt}
            },
            checkPassword:(string, passObj)=>{
                let ms5Str = crypto.createHash('sha1').update(string).digest('hex');
                let salt = passObj.salt;
                let password = crypto.createHash('sha1').update(ms5Str + salt).digest('hex');
                if(password === passObj.password){
                    return true
                } else {
                    return false
                }
            },
            res: async (ctx, num, data = null)=>{
                ctx.body = {code:num, message:code[num], data};
                switch (num.substr(0,1)) {
                    case "0":
                        ctx.status = 200;
                        break;
                    case "1":
                        ctx.status = 400;
                        break;
                }
                return;
            },
            event: new EventEmitter(),
            smsClient: new SMSClient({accessKeyId:"1Oe63h7MuDdPAHY8", secretAccessKey: "G1S3yXKPmDDuC0Lp1KbFZSz2TKJmao"}),
            ObjectId : require('mongodb').ObjectID
        };
        //初始化管理员账户
        const admin = new mongo(mydb, 'backend.admin');
        let adminInfo = await admin.findOne({name:"vino"});
        if(!adminInfo){
            let passObj = fun.encord2md5("89775640");
            await admin.insert({name:"vino", pass:passObj});
        }
        //初始化芝麻账户
        const zhima = new mongo(mydb, 'backend.zhima.account');
        let zhimaStats = await zhima.stats();
        const seSameAccount = [
            { tel: "13221740540", password: "5f5kci9gx8mznqoa", name: "KatherinaTorruellas", "user_id": 43234, "pack_id": 20733 }
        ];
        if (zhimaStats instanceof Error) {
            for (a of seSameAccount) {
                await zhima.insert(a);
            }
        }
        //初始化使用记录
        const ipRecord = new mongo(mydb, 'app.proxy.ip.record');
        let ipRecordStats = await ipRecord.stats();
        if (ipRecordStats instanceof Error) {
            await ipRecord.ensureIndex({ url: 1 });
            await ipRecord.ensureIndex({ uid: 1 });
            await ipRecord.ensureIndex({ time: 1 }, { expireAfterSeconds: 7 * 24 * 60 * 60 * 1000 });
        }
        //初始化缓存记录
        const userCache = new mongo(mydb, 'app.user.cache');
        let userCacheStats = await userCache.stats();
        if (userCacheStats instanceof Error) {
            await userCache.ensureIndex({ uid: 1 });
            await userCache.ensureIndex({ url: 1 });
        }
    }catch (e) {
        throw e;
    }
};